package com.zyf.wjy.service;

import com.zyf.wjy.dao.FarmingRecordDao;
import com.zyf.wjy.entity.FarmingRecord;
import com.zyf.wjy.util.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 农事记录服务类
 */
@Service
public class FarmingRecordService {
    
    @Autowired
    private FarmingRecordDao farmingRecordDao;
    
    @Autowired
    private MaterialService materialService;
    
    /**
     * 查询所有农事记录
     */
    public List<FarmingRecord> findAll() {
        return farmingRecordDao.findAll();
    }
    
    /**
     * 根据ID查询
     */
    public FarmingRecord findById(Long id) {
        return farmingRecordDao.findById(id);
    }
    
    /**
     * 根据地块ID查询
     */
    public List<FarmingRecord> findByFieldId(Long fieldId) {
        return farmingRecordDao.findByFieldId(fieldId);
    }
    
    /**
     * 根据农事类型查询
     */
    public List<FarmingRecord> findByFarmingType(String farmingType) {
        return farmingRecordDao.findByFarmingType(farmingType);
    }
    
    /**
     * 保存农事记录
     */
    public FarmingRecord save(FarmingRecord record) {
        if (record.getId() == null) {
            record.setRecordCode(CodeGenerator.generateRecordCode());
            record.setCreateTime(LocalDateTime.now());
        }
        
        FarmingRecord saved = farmingRecordDao.save(record);
        
        // 如果使用了农资，更新农资库存
        if (saved.getMaterialId() != null && saved.getQuantity() != null && saved.getQuantity() > 0) {
            materialService.stockOut(saved.getMaterialId(), saved.getQuantity());
        }
        
        return saved;
    }
    
    /**
     * 删除农事记录
     */
    public boolean deleteById(Long id) {
        return farmingRecordDao.deleteById(id);
    }
}

